/**
 * Either函子
 */

// Left函子用来记录异常信息
class Left<T> {
  static of<T> (value: T) {
    return new Left(value)
  }

  private _value: T
  constructor (value: T) {
    this._value = value
  }

  map (fn: (value: T) => T): Left<T> {
    return this
  }
}

class Right<T> {
  static of<T> (value: T) {
    return new Right(value)
  }

  private _value: T
  constructor (value: T) {
    this._value = value
  }

  map (fn: (value: T) => T): Right<T> {
    return Right.of(fn(this._value))
  }
}

let r1 = Right.of(12).map(x => x + 2)
let r2 = Left.of(12).map(x => x + 2)
console.log(r1)
console.log(r2)

const parseJSON = str => {
  try {
    return Right.of(JSON.parse(str))
  } catch (e) {
    return Left.of({error: e.message})
  }
}

let r = parseJSON('{name: zs}')
        .map((x: any) => x.name.toUpperCase())
console.log(r)

// let r = parseJSON('{"name": "zs"}')
//         .map(x => x.name.toUpperCase())
// console.log(r)
export {}
